{{define "article.add"}}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>文章添加</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/statics/third-pkg/layui/css/layui.css">
    <link rel="stylesheet" href="/statics/admin/css/public.css" media="all">
    <style>
        body {
            background-color: #ffffff;
        }
    </style>
</head>

<body>
    <div class="layui-form layuimini-form">
        <div class="layui-form-item">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
                <input type="radio" name="status" value="1" title="关闭" checked="">
                <input type="radio" name="status" value="2" title="开启">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否推荐</label>
            <div class="layui-input-block">
                <input type="radio" name="is_recommend" value="1" title="否" checked="">
                <input type="radio" name="is_recommend" value="2" title="是">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">标题</label>
            <div class="layui-input-block">
                <input type="text" name="title" lay-verify="required" lay-reqtext="标题不能为空" placeholder="请输入标题" value="" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">分类</label>
            <div class="layui-input-block">
                <input type="hidden" lay-verify="required" name="category_id">
                <input type="text"  lay-verify="required" readonly="true"  name="category_name"  autocomplete="off" class="layui-input" id="categoryName">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">标签</label>
            <div class="layui-input-block">
                <input type="hidden"  lay-verify="required" readonly="true" lay-reqtext="标签不能为空"  name="tag_ids"  autocomplete="off" class="layui-input" id="tagName">
                <div class="layui-btn-container tag" lay-filter="article_tags" lay-allowclose="true">
                    <button class="button-new-tag layui-btn layui-btn-primary layui-btn-sm" data-type="tagAdd">'<i class="layui-icon layui-icon-add-1"></i>添加标签</button>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">权重</label>
            <div class="layui-input-block">
                <input type="number" name="weight"  placeholder="请输入权重" value="" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">内容</label>
            <div class="layui-input-block">
                <div id="editor" style="margin: 20px 0 50px 0">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
            </div>
        </div>
    </div>
    <script src="/statics/third-pkg/layui/layui.js"></script>
    <script src="/statics/admin/js/lay-config.js?v=2.0" charset="utf-8"></script>
    <script>

        layui.use(['tag','form','request','layer','miniTab',"common","tableSelect","popTable","wangEditor"], function() {
            var form = layui.form,
                layer = layui.layer,
                miniTab = layui.miniTab,
                $=layui.$,
                common=layui.common,
                tableSelect = layui.tableSelect,
                popTable = layui.popTable,
                wangEditor = layui.wangEditor,
                tag=layui.tag,
                request=layui.request;
                var editor = new wangEditor('#editor');
                editor.customConfig.uploadImgServer = "../api/upload.json";
                editor.customConfig.uploadFileName = 'image';
                editor.customConfig.pasteFilterStyle = false;
                editor.customConfig.uploadImgMaxLength = 5;
                editor.customConfig.uploadImgHooks = {
                    // 上传超时
                    timeout: function (xhr, editor) {
                        layer.msg('上传超时！')
                    },
                    // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                    customInsert: function (insertImg, result, editor) {
                        console.log(result);
                        if (result.code == 1) {
                            var url = result.data.url;
                            url.forEach(function (e) {
                                insertImg(e);
                            })
                        } else {
                            layer.msg(result.msg);
                        }
                    }
                };
                editor.customConfig.customAlert = function (info) {
                    layer.msg(info);
                };
                editor.create();

                tableSelect.render({
                    elem: '#categoryName',	//定义输入框input对象 必填
                    checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
                    searchKey: 'name',
                    searchPlaceholder: '关键词搜索',	//搜索输入框的提示文字 默认关键词搜索
                    table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                        url: '/admin/article-category/list-data',
                        cols: [[
                            {type: 'radio' },
                            {field: 'id',
                                width: 80,
                                title: 'ID',
                                sort: true
                            }, {
                                field: 'name',
                                width: 200,
                                title: '分类名称'
                            }, {
                                field: 'created_at',
                                width: 200,
                                title: '创建时间'
                            }]]
                    },
                    done: function (elem, data) {
                        if (data.isAll ==true){
                            var cate_name=data.data.map(function (item) {
                                return item.name
                            }).pop()
                            var cate_id=data.data.map(function (item) {
                                return item.id
                            }).pop()

                            $(elem).val(cate_name);
                            $(elem).prev().val(cate_id)
                        }
                    }
                })
            //触发事件
            var active = {
                tagAdd: function (othis,data) {
                    var ids=[];
                    if(othis !=undefined){
                        var siblings = $(othis).siblings();
                        siblings.each(function (i,v) {
                            ids.push(Number.parseInt($(v).attr('lay-id')))
                        })
                    }
                    var old_val = $("input[name='tag_ids']").val();
                    var tag_ids=data.map(function (item){
                        return item.id;
                    }).join(',');
                    if(old_val){
                        tag_ids=old_val+","+tag_ids;
                    }
                    $("input[name='tag_ids']").val(tag_ids);
                    for (const dataKey in data) {
                        if(!ids.includes(data[dataKey].id)){
                            //新增一个Tag项
                            tag.add('article_tags', {
                                text: data[dataKey].name //用于演示
                                , id: data[dataKey].id
                                ,background_color:data[dataKey].color
                            })
                        }
                    }

                }
            };
            tag.render("article_tags", {
                skin: 'layui-btn layui-btn-primary layui-btn-sm', //标签样式
                tagText: '<i class="layui-icon layui-icon-add-1"></i>添加标签' //标签添加按钮提示文本
            });
            $(".button-new-tag").click(function () {
                var val = $("input[name='tag_ids']").val();
                var split = val.split(',').map(function (item){
                    return Number.parseInt(item);
                });
                var _this=this;
                popTable.open({
                    inputId: 'ptCode',    //选中的值填入父层的字段id
                    title: '文章标签',  //弹窗标题
                    url: '/admin/tag/list-data', //数据url
                    field: 'username',       //选择哪个字段的值
                    keyName: 'name',  //向后台服务器发送搜索的字段名，默认是keywords
                    offset: ['50px;', '250px;'],
                    checkedId:split,
                    request: {pageName: 'page',limitName: 'limit'},
                    cols: [[
                        {type: 'checkbox', },
                        {field: 'id',
                            width: 80,
                            title: 'ID',
                            sort: true
                        }, {
                            field: 'name',
                            width: 200,
                            title: '名称',
                            templet:function (d) {
                                return `
                        <div class="layui-btn-container tag">
    <button type="button" class="tag-item tag-item-normal layui-btn layui-btn-primary layui-btn-sm" style="background-color:${d.color};color:#fff">${d.name}</button>
</div>
                        `;
                            }
                        }, {
                            field: 'created_at',
                            width: 200,
                            title: '创建时间'
                        }]],
                    chooseSuccess: function (data) {
                        var othis = $(_this);
                        active["tagAdd"] ? active["tagAdd"].call(_this, othis,data.data) : '';
                    }

                });

            })
            tag.on('delete(article_tags)', function(data) {
                var val = $("input[name='tag_ids']").val();
                var split = val.split(',');
                split.splice(data.index,1);
                val=split.join(',');
                $("input[name='tag_ids']").val(val)
            });
            //监听提交
            form.on('submit(saveBtn)', function(data) {
                var subdata={
                    ...data.field,
                    "weight":Number.parseInt(data.field["weight"]),
                    "category_id":Number.parseInt(data.field['category_id']),
                    "content":editor.txt.html(),
                    "is_recommend":Number.parseInt(data.field['is_recommend']),
                    "status":Number.parseInt(data.field['status'])
                }
                request.post('admin/article/add',subdata).then(function (response) {
                    if(response.data.code==0){
                        localStorage.setItem("article",common.generateUUID())
                        layer.msg('添加文章成功',{
                            time:1000
                        },function (){
                            miniTab.deleteCurrentByIframe();
                            var index = parent.layer.getFrameIndex(window.name);
                            window.location.href="/admin/article/list";
                            parent.layer.close(index);
                        })
                    }else{
                        layer.msg(response.data.msg);
                    }
                }).catch(function (error) {
                    console.log(error)
                    layer.msg('提交失败');
                });

            });

        });
    </script>
</body>

</html>
{{ end }}